const basicAuth = require("basic-auth");
const jwt = require("jsonwebtoken");
const config = require("../config/config");
const { ScopeType } = require("../lib/enum");

class Auth {
  constructor(level = ScopeType.USER) {
    // super();
    this.level = level;
    Auth.USER = ScopeType.USER;
    Auth.ADMIN = ScopeType.ADMIN;
    Auth.SUPER = ScopeType.SUPER;
  }
  get m() {
    return async (ctx, next) => {
      const token = basicAuth(ctx.req);
      let errMsg = "token错误";
      if (!token || token.name === "") {
        throw new global.errs.Forbbiden(errMsg);
      }

      try {
        var auth = jwt.verify(token.name, config.security.secretKey);
      } catch (error) {
        if (error.name == "TokenExpiredError") {
          errMsg = "token已过期";
        }
        throw new global.errs.Forbbiden(errMsg);
      }

      if (auth.scope < this.level) {
        errMsg = "权限不足";
        throw new global.errs.Forbbiden(errMsg);
      }

      ctx.auth = {
        uId: auth.uid,
        scope: auth.scope,
      };
      await next();
    };
  }

  static async verifyToken(token) {
    let errMsg = "token错误";
    try {
      var auth = jwt.verify(token, config.security.secretKey);
    } catch (error) {
      if (error.name == "TokenExpiredError") {
        errMsg = "token已过期";
      }
      throw new global.errs.Forbbiden(errMsg);
    }
    return true
  }
}
module.exports = {
  Auth,
};
